package dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

import model.Item;

public class ItemData {
	public static void addItem(long idItem, String nameItem , double price,String avatarItem){
		Connection con = DbConnection.getConnect();
		String sql = "INSERT INTO item VALUES(?,?,?,?)";
		PreparedStatement pre;

		try {
			pre = con.prepareStatement(sql);
			pre.setLong(1, idItem);
			pre.setString(2, nameItem);
			pre.setString(3, avatarItem);
			pre.setDouble(4, price);
			pre.executeUpdate();

		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	public static ArrayList<Item> getListItem(){
		
		ArrayList<Item> list = new ArrayList<>();
		Connection con = DbConnection.getConnect();
		String sql = "SELECT * FROM item ";
		PreparedStatement pre;

		try {
			pre = con.prepareStatement(sql);
			  ResultSet rs = pre.executeQuery();
			while(rs.next()){
				long idItem = rs.getLong("idItem");
				String nameItem = rs.getString("nameItem");
				String avatarItem = rs.getString("avatarItem");
				double price = rs.getLong("priceItem");
				Item item	= new Item(idItem, nameItem, price, avatarItem);
				list.add(item);
			}

		} catch (SQLException e) {
			e.printStackTrace();
		}
		return list;
		
	}
	public static Item getItem(long idItem){
		Connection con = DbConnection.getConnect();
		String sql = "SELECT * FROM item WHERE idItem = ?";
		Item item = null;
		PreparedStatement pre;

		try {
			pre = con.prepareStatement(sql);
			pre.setLong(1, idItem);
			  ResultSet rs = pre.executeQuery();
			  
			while(rs.next()){
				String nameItem = rs.getString("nameItem");
				String avatarItem = rs.getString("avatarItem");
				double price = rs.getLong("priceItem");
				 item	= new Item(idItem, nameItem, price, avatarItem);
			}

		} catch (SQLException e) {
			e.printStackTrace();
		}
		
		return item;
		
	}
	public static void delItem(long idItem){
		Connection con = DbConnection.getConnect();
		String sql = "DELETE FROM item WHERE idItem = ? ";
		PreparedStatement pre;

		try {
			pre = con.prepareStatement(sql);
			pre.setLong(1, idItem);
			pre.executeUpdate();
			pre.close();
			con.close();
		} catch (SQLException e) {
			e.printStackTrace();}
		}
	public static void main(String[] args) {
		ArrayList<Item> list = getListItem();
		for (int i = 0; i < list.size(); i++) {
			System.out.println(list.get(i).getNameItem());
		}
	}

}
